﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class BufferedConsole : IDisposable
{
    private StringBuilder buffer;
    private int capacity;

    public int Capacity
    {
        get { return capacity; }
        set { capacity = value; }
    }

    public BufferedConsole(int capacity)
    {
        buffer = new StringBuilder(capacity);
    }

    public BufferedConsole()
        : this(25)
    {
    }

    ~BufferedConsole()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public void Write(string s)
    {
        if (buffer.Length + s.Length > buffer.Capacity)
        {
            int availableBytes = buffer.Capacity - buffer.Length;
            buffer.Append(s.Substring(0, availableBytes));
            Flush();
            Write(s.Substring(availableBytes));
        }
        else
        {
            buffer.Append(s);
        }
    }

    private void Dispose(bool disposing)
    {
        Flush();
        buffer = null;
    }

    private void Flush()
    {
        if (buffer.Length > 0)
        {
            Console.WriteLine(buffer.ToString());
            buffer.Clear();
        }
    }
}

